
Imports System
Imports System.Collections
Imports System.Data.SqlClient
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports _2bMatesSite.Common

Imports System.Data
'using System.Security;
Imports System.Web.Security

Namespace _2bMatesSite.BO
	''' <summary>
	''' Represends a 2bmates user.
	''' </summary>
	Public Class User
		'
		' Members
		'

		Protected id As Integer
		Protected name As String
		Protected lastName As String
		Protected email As String
		Protected nickName As String
		Protected passHash As String
		Protected gender As Integer
		' link to an enum
		' 1 - male; 2 - female
		Protected birthDay As DateTime
		Protected genderPreference As Integer
		' 1 - Males; 2 - Females; 3 -both
		' Activity preferences - 0-unchecked, 1-checked
		Protected matesSR As Boolean
		Protected matesPen As Boolean
		Protected matesFriends As Boolean
		Protected matesDating As Boolean
		Protected matesAP As Boolean
		Protected matesJHO As Boolean
		Protected refererID As Integer
		' User ID of 2bMates User who has recommended the site
		Protected showOnline As Boolean
		Protected interests As String
		Protected coutryID As Integer
		Protected city As String
		Protected zip As String
		Protected placeOfBirth As String
		Protected maritalStatus As Integer
		' 1-Single/Separated/Divorced; 2-In a relationship; 3-Married; 4-Open marriage
		Protected occupation As String
		Protected templateID As Integer
		Protected bgImageURL As String
		Protected wavURL As String
		Protected defaultPictureID As Integer
		Protected aboutMe As String
		Protected lookingFor As String
		Protected affiliations As String
		Protected companies As String
		Protected schools As String
		Protected songURL1 As String
		Protected songURLName1 As String
		Protected songURL2 As String
		Protected songURLName2 As String
		Protected songURL3 As String
		Protected songURLName3 As String
		Protected imageURL As String
		Protected imageURLName As String
		Protected music As String
		Protected books As String
		Protected tv As String
		Protected movies As String
		Protected registrationDate As DateTime
		Protected editDate As DateTime
		Protected loginDate As DateTime
		Protected enableEmailNotify As Boolean
		Protected enableGroupEmailNotify As Boolean
		Protected enableNewsletter As Boolean
		' 0 - subscribed, 1 - unsubscribed
		Protected status As Integer
		' 0 - unconfirmed; 1 - active; 2 - locked; 3 - administrator
		Protected timesViewed As Integer
		Protected approveComments As Boolean
		' 0 - ask for approval, 1 - auto approve
		Protected approveBlogComments As Boolean
		' 0 - ask for approval, 1 - auto approve
		Protected approveFriends As Boolean
		' 0 - ask for approval - name/email, 1 - auto approve
		Protected forumPassHash As String
		Protected chatPass As String

		Protected pictures As ArrayList

		'
		' User constructors
		'

		' Loads user from a data reader
		' NOTE:	To load and existing user by email,ID etc
		'			use the Users methos (e.g. Users.GetUserByID)
		Public Sub New(ByVal dr As SqlDataReader)
			LoadFromReader(dr)
		End Sub

		' Creates a new user of the system
		Public Sub New(ByVal userEmail As String, ByVal userPass As String, ByVal refererID As Integer)
			Init(userEmail, userPass, refererID)
		End Sub

		' Creates a new user of the system without a referer
		Public Sub New(ByVal userEmail As String, ByVal userPass As String)
			Init(userEmail, userPass, -1)
		End Sub


		'
		' Properties
		'

		Public ReadOnly Property ID() As Integer
			Get
				Return id
			End Get
		End Property

		Public Property Name() As String
			Get
				Return name
			End Get

			Set
				name = value
			End Set
		End Property

		Public Property LastName() As String
			Get
				Return lastName
			End Get

			Set
				lastName = value
			End Set
		End Property

		Public Property Email() As String
			Get
				Return email
			End Get
			Set
				email = value
			End Set
		End Property

		Public Property NickName() As String
			Get
				Return nickName
			End Get

			Set
				nickName = value
			End Set
		End Property

		Public Property PassHash() As String
			Get
				Return passHash
			End Get

			Set
				passHash = value
			End Set
		End Property

		Public WriteOnly Property Password() As String
			Set
				passHash = Users.ComputeUserHash(email, value)
				'forumPassHash = FormsAuthentication.HashPasswordForStoringInConfigFile(value,"md5");
				chatPass = value
			End Set
		End Property

		Public Property Gender() As Integer
			Get
				Return gender
			End Get
			Set
				gender = value
			End Set
		End Property

		Public Property BirthDay() As DateTime
			Get
				Return birthDay
			End Get

			Set
				birthDay = value
			End Set
		End Property

		Public Property GenderPreference() As Integer
			Get
				Return genderPreference
			End Get

			Set
				genderPreference = value
			End Set
		End Property

		' Activity preferences

		Public Property MatesSR() As Boolean
			Get
				Return matesSR
			End Get
			Set
				matesSR = value
			End Set
		End Property

		Public Property MatesPen() As Boolean
			Get
				Return matesPen
			End Get
			Set
				matesPen = value
			End Set
		End Property

		Public Property MatesFriends() As Boolean
			Get
				Return matesFriends
			End Get
			Set
				matesFriends = value
			End Set
		End Property

		Public Property MatesDating() As Boolean
			Get
				Return matesDating
			End Get
			Set
				matesDating = value
			End Set
		End Property

		Public Property MatesAP() As Boolean
			Get
				Return matesAP
			End Get
			Set
				matesAP = value
			End Set
		End Property

		Public Property MatesJHO() As Boolean
			Get
				Return matesJHO
			End Get
			Set
				matesJHO = value
			End Set
		End Property

		Public Property RefererID() As Integer
			Get
				Return refererID
			End Get
			Set
				refererID = value
			End Set
		End Property

		Public Property ShowOnline() As Boolean
			Get
				Return showOnline
			End Get

			Set
				showOnline = value
			End Set
		End Property

		Public Property Interests() As String
			Get
				Return interests
			End Get

			Set
				interests = value
			End Set
		End Property

		Public Property CountryID() As Integer
			Get
				Return coutryID
			End Get

			Set
				coutryID = value
			End Set
		End Property

		Public Property City() As String
			Get
				Return city
			End Get

			Set
				city = value
			End Set
		End Property

		Public Property ZipCode() As String
			Get
				Return zip
			End Get

			Set
				zip = value
			End Set
		End Property

		Public Property PlaceOfBirth() As String
			Get
				Return placeOfBirth
			End Get

			Set
				placeOfBirth = value
			End Set
		End Property

		Public Property MaritalStatus() As Integer
			Get
				Return maritalStatus
			End Get

			Set
				maritalStatus = value
			End Set
		End Property

		Public Property Occupation() As String
			Get
				Return occupation
			End Get

			Set
				occupation = value
			End Set
		End Property

		Public Property TemplateID() As Integer
			Get
				Return templateID
			End Get

			Set
				templateID = value
			End Set
		End Property

		Public Property Template() As Template
			Get
				Return Utils.GetTemplateByID(TemplateID)
			End Get

			Set
				templateID = value.ID
			End Set
		End Property

		Public Property BGImageURL() As String
			Get
				Return bgImageURL
			End Get

			Set
				bgImageURL = value
			End Set
		End Property

		Public Property WAVURL() As String
			Get
				Return wavURL
			End Get

			Set
				wavURL = value
			End Set
		End Property

		Public Property DefaultPictureID() As Integer
			Get
				Return defaultPictureID
			End Get

			Set
				defaultPictureID = value
			End Set
		End Property

		Public Property AboutMe() As String
			Get
				Return aboutMe
			End Get

			Set
				aboutMe = value
			End Set
		End Property

		Public Property LookingFor() As String
			Get
				Return lookingFor
			End Get

			Set
				lookingFor = value
			End Set
		End Property
		Public Property Affiliations() As String
			Get
				Return affiliations
			End Get

			Set
				affiliations = value
			End Set
		End Property

		Public Property Companies() As String
			Get
				Return companies
			End Get

			Set
				companies = value
			End Set
		End Property

		Public Property Schools() As String
			Get
				Return schools
			End Get

			Set
				schools = value
			End Set
		End Property

		Public Property SongURL1() As String
			Get
				Return songURL1
			End Get

			Set
				songURL1 = value
			End Set
		End Property

		Public Property SongURLName1() As String
			Get
				Return songURLName1
			End Get

			Set
				songURLName1 = value
			End Set
		End Property

		Public Property SongURL2() As String
			Get
				Return songURL2
			End Get

			Set
				songURL2 = value
			End Set
		End Property

		Public Property SongURLName2() As String
			Get
				Return songURLName2
			End Get

			Set
				songURLName2 = value
			End Set
		End Property

		Public Property SongURL3() As String
			Get
				Return songURL3
			End Get

			Set
				songURL3 = value
			End Set
		End Property

		Public Property SongURLName3() As String
			Get
				Return songURLName3
			End Get

			Set
				songURLName3 = value
			End Set
		End Property

		Public Property ImageURL() As String
			Get
				Return imageURL
			End Get

			Set
				imageURL = value
			End Set
		End Property

		Public Property ImageURLName() As String
			Get
				Return imageURLName
			End Get

			Set
				imageURLName = value
			End Set
		End Property

		Public Property Music() As String
			Get
				Return music
			End Get

			Set
				music = value
			End Set
		End Property

		Public Property Books() As String
			Get
				Return books
			End Get

			Set
				books = value
			End Set
		End Property

		Public Property TV() As String
			Get
				Return tv
			End Get

			Set
				tv = value
			End Set
		End Property

		Public Property Movies() As String
			Get
				Return movies
			End Get

			Set
				movies = value
			End Set
		End Property

		Public ReadOnly Property RegistrationDate() As DateTime
			Get
				Return registrationDate
			End Get
		End Property

		Public Property EditDate() As DateTime
			Get
				Return editDate
			End Get
			Set
				editDate = value
			End Set
		End Property

		Public ReadOnly Property LastLoginDate() As DateTime
			Get
				Return loginDate
			End Get
		End Property

		Public Property EnableEmailNotify() As Boolean
			Get
				Return enableEmailNotify
			End Get
			Set
				enableEmailNotify = value
			End Set
		End Property

		Public Property EnableGroupEmailNotify() As Boolean
			Get
				Return enableGroupEmailNotify
			End Get
			Set
				enableGroupEmailNotify = value
			End Set
		End Property

		Public Property EnableNewsletter() As Boolean
			Get
				Return enableNewsletter
			End Get
			Set
				enableNewsletter = value
			End Set
		End Property

		Public ReadOnly Property Status() As Integer
			Get
				Return status
			End Get
		End Property

		Public Property TimesViewed() As Integer

			Get
				Return timesViewed
			End Get

			Set
				timesViewed = value
			End Set
		End Property

		Public Property ApproveComments() As Boolean
			Get
				Return approveComments
			End Get

			Set
				approveComments = value
			End Set
		End Property

		Public Property ApproveBlogComments() As Boolean
			Get
				Return approveBlogComments
			End Get

			Set
				approveBlogComments = value
			End Set
		End Property

		Public Property ApproveFriends() As Boolean
			Get
				Return approveFriends
			End Get

			Set
				approveFriends = value
			End Set
		End Property

		'
		' Public methods
		'

		' Save the modifications to the user made so far
		' If it's a new user inserts it into the database
		Public Sub Save()
			If id < 0 Then
				If Constants.HAS_FORUM = Constants.SHOW_ON Then
					SaveUserToChatDB()
					SaveUserToForumDB()
				End If

				DoInsert()
			Else
				DoUpdate()
			End If
		End Sub

		' Refresh the user's properties, based on it's email
		' NOTE: does nothing if it's a new user
		Public Sub Refresh()
			If id <> -1 Then
				DoRefresh()
			End If
		End Sub

		' Register user account
		Public Sub SetUnconfirmed()
			Me.status = Users.STATUS_UNCONFIRMED
		End Sub

		' Activate user account
		Public Sub SetActive()
			Me.status = Users.STATUS_ACTIVE
		End Sub

		' Lock user account
		Public Sub SetLocked()
			Me.status = Users.STATUS_LOCKED
		End Sub

		' Make the user an admin
		Public Sub SetAdmin()
			Me.status = Users.STATUS_ADMIN
		End Sub

		' Deletes the user and all releated information from the site's database
		' NOTE:	initializes the object as a  new non-existing user (id = -1)
		'			with the same email, password, and referer as the current one
		'			thus calling Save after UnRegister would result in creating a brand new user
		Public Sub UnRegister(ByVal userFeedBack As String)
			' Send mail with feedback to the admin
			Users.SendFeedback(userFeedBack, Me)

			' Do delete the user
			DoDelete()
		End Sub

		Public ReadOnly Property BlockedUsers() As UsersBlocked
			Get
				Return New UsersBlocked(Me)
			End Get
		End Property

		Public ReadOnly Property BlockingUsers() As UsersBlocked
			Get
				Return New UsersBlocked(Me, True)
			End Get
		End Property

		Public ReadOnly Property FavoriteUsers() As UsersFavorites
			Get
				Return New UsersFavorites(Me)
			End Get
		End Property

		Public ReadOnly Property FavoriteGroups() As FavoriteGroups
			Get
				Return New FavoriteGroups(Me)
			End Get
		End Property

		Public Function AcceptCreateFriendshipNoException(ByVal friendID As Integer) As DirectFriend.InviteStatus
			Dim status As DirectFriend.InviteStatus = DirectFriend.InviteStatus.dsNonExisting

			Try
				' Catch friendship rules exceptions
				status = AcceptCreateFriendship(friendID)
					' And do nothing
			Catch generatedExceptionName As FriendshipException
			End Try

			Return status
		End Function

		' Used for both inviting and accepting a friend
		' NOTE: throws an exception if the invitation was already accepted
		Public Function AcceptCreateFriendship(ByVal friendID As Integer) As DirectFriend.InviteStatus
			If BO.UsersBlocked.IsUserBlockedBy(id, friendID) Then
				Throw New FriendshipException("This user has blocked you.")
			End If

			Dim df As DirectFriend = Users.GetFriendInvitation(id, friendID)
			df.IncrementStatus()
			df.Save()

			Return df.Status
		End Function


		' Used for directly creating and acceptin friendship. Only in j
		Public Function AcceptCreateFriendshipDirectly(ByVal friendID As Integer) As DirectFriend.InviteStatus
			If BO.UsersBlocked.IsUserBlockedBy(id, friendID) Then
				Throw New FriendshipException("This user has blocked you.")
			End If

			Dim df As DirectFriend = Users.GetFriendInvitation(id, friendID, True)
			df.Save()

			Return df.Status
		End Function


		' Used to reject friendship
		' NOTE:
		' - deletes the friendship relation
		'	in case such was already established (accepted by both parties)
		' - keeps it with a "rejected" status if it was an actual invitation
		' - throws an exception if it is a non-existing or already rejected relationship
		Public Function RejectFriendship(ByVal friendID As Integer) As DirectFriend.InviteStatus
			Dim df As DirectFriend = Users.GetFriendInvitation(id, friendID)
			df.DecrementStatus()
			df.Save()

			Return df.Status
		End Function

		Public ReadOnly Property Invitations() As UserInvitations
			Get
				Return New UserInvitations(id, False)
			End Get
		End Property

		Public ReadOnly Property PendingInvitations() As UserInvitations
			Get
				Return New UserInvitations(id, False, True)
			End Get
		End Property

		Public ReadOnly Property OutgoingInvitations() As UserInvitations
			Get
				Return New UserInvitations(id, True)
			End Get
		End Property

		Public ReadOnly Property DirectFriends() As UsersFriends
			Get
				Return New UsersFriends(Me)
			End Get
		End Property

		Public Property DefaultPicture() As UserPicture
			Get
				Return GetPicture(DefaultPictureID)
			End Get
			Set
				If value = Nothing Then
					defaultPictureID = -1
				Else
					If GetPicture(value.ID) <> Nothing Then
						defaultPictureID = value.ID
					End If
				End If
			End Set
		End Property

		Public Function GetPicture(ByVal picID As Integer) As UserPicture
			Dim pic As UserPicture = Nothing

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand("SELECT * FROM Pictures WHERE UID=@UID AND ID=@ID")
				cmd.Connection = conn

				cmd.Parameters.Add("@UID", id)
				cmd.Parameters.Add("@ID", picID)

				Dim dr As SqlDataReader = cmd.ExecuteReader()

				If dr.Read() Then
					pic = New UserPicture(dr)
				End If
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return pic
		End Function

		Public Function GetPictures() As ArrayList
			Dim pics As New ArrayList()

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand(GetPicturesSQL())
				cmd.Connection = conn

				cmd.Parameters.Add("@UID", id)

				Dim dr As SqlDataReader = cmd.ExecuteReader()

				While dr.Read()
					pics.Add(New UserPicture(dr))
				End While
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return pics
		End Function

		Public Function GetPicturesTotalLength() As Integer
			Dim totalLength As Integer = 0

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand(GetPicturesTotalLengthSQL())
				cmd.Connection = conn

				cmd.Parameters.Add("@UID", id)

				Dim dr As SqlDataReader = cmd.ExecuteReader()
				If dr.Read() Then
					totalLength = DBManager.GetNZInt32(dr, "TotalLength")
				End If
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return totalLength
		End Function

		Public Function AddPicture(ByVal picStream As Stream, ByVal picName As String, ByVal picDesc As String) As UserPicture
			' Load the original picture
			Dim img As New Bitmap(picStream)

			' Calculate it's new size
			Dim newSize As Size = Pictures.FitSize(img.Size, New Size(Constants.PICTURE_MAX_WIDTH, Constants.PICTURE_MAX_HEIGHT), True)

			' Resize if needed
			If Not newSize.Equals(img.Size) Then
				img = Pictures.ResizeBitmap(img, newSize)
			End If

			' store the image and create an instance of the user's Picture object
			Dim pic As New UserPicture(Me, img, picName, picDesc)
			pic.Save()

			Return pic
		End Function

		Public Sub DeletePicture(ByVal pic As UserPicture)
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				' Delete the picture
				Dim cmd As New SqlCommand(GetDeletePictureSQL())
				cmd.Connection = conn

				cmd.Parameters.Add("@ID", pic.ID)

				Dim rows As Integer = cmd.ExecuteNonQuery()
				Debug.Assert(rows = 1)
			Finally
				conn.Close()
			End Try
		End Sub

		Public Sub DeleteSong(ByVal SongID As String, ByVal FileFolderPath As String)
			'procedure added by ivan - deletes users song or clip
			'the procedure removes the data from the database nadee deleted the file form the server's harddisk
			Dim l_sFilePath As String = ""

			Select Case SongID
				Case "1"
					l_sFilePath = FileFolderPath + SongURL1
					If File.Exists(l_sFilePath) Then
						File.Delete(l_sFilePath)
					End If
					SongURL1 = ""
					SongURLName1 = ""
					Save()
					Exit Select
				Case "2"

					l_sFilePath = FileFolderPath + SongURL2
					If File.Exists(l_sFilePath) Then
						File.Delete(l_sFilePath)
					End If
					SongURL2 = ""
					SongURLName2 = ""
					Save()
					Exit Select
				Case "3"

					l_sFilePath = FileFolderPath + SongURL3
					If File.Exists(l_sFilePath) Then
						File.Delete(l_sFilePath)
					End If
					SongURL3 = ""
					SongURLName3 = ""
					Save()
					Exit Select
			End Select

		End Sub

		Public Sub AddComment(ByVal fromUserID As Integer, ByVal comment As String)
			Dim usrComment As New UserComment(id, fromUserID, comment)
			If approveComments Then
				'usrComment.CommentStatus = UserComment.Status.ucsAccepted;
				usrComment.CommentStatus = UserComment.Status.ucsNewAccepted
			End If
			AddComment(usrComment)
		End Sub

		Public Sub AddComment(ByVal comment As UserComment)
			If comment.AboutUserID <> id Then
				Throw New Exception("Can't add comments to a user about other users.")
			End If

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim sql As String = "INSERT INTO UserComments (Comment, PostedByUID, AboutUID, Status, Date)" + Environment.NewLine
				sql += "VALUES (@Comment, @PostedByUID, @AboutUID, @Status, @Date)" + Environment.NewLine

				Dim cmd As New SqlCommand(sql)
				cmd.Connection = conn
				cmd.Parameters.Add("@Comment", comment.Comment)
				cmd.Parameters.Add("@PostedByUID", comment.PostedByUserID)
				cmd.Parameters.Add("@AboutUID", comment.AboutUserID)
				cmd.Parameters.Add("@Status", DirectCast(comment.CommentStatus, Integer))
				cmd.Parameters.Add("@Date", comment.[Date])

				cmd.ExecuteNonQuery()

				' Send the receiver a notification
				Users.SendUserCommentNotification(Users.GetUserByID(comment.AboutUserID), Users.GetUserByID(comment.PostedByUserID))
			Finally
				conn.Close()
			End Try
		End Sub

		Public Sub RemoveComment(ByVal commentID As Integer)
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim sql As String = "DELETE FROM UserComments WHERE ID=@ID" + Environment.NewLine
				Dim cmd As New SqlCommand(sql)
				cmd.Connection = conn

				cmd.Parameters.Add("@ID", commentID)

				cmd.ExecuteNonQuery()
			Finally
				conn.Close()
			End Try
		End Sub

		Public Sub ApproveComment(ByVal commentID As Integer)
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim sql As String = "UPDATE UserComments SET Status=" + DirectCast(UserComment.Status.ucsAccepted, Integer) + " WHERE ID=@ID" + Environment.NewLine
				Dim cmd As New SqlCommand(sql)
				cmd.Connection = conn

				cmd.Parameters.Add("@ID", commentID)

				cmd.ExecuteNonQuery()
			Finally
				conn.Close()
			End Try
		End Sub

		' This function is used to set all comments as read, when the user has set ApproveComments = true
		Public Sub ApproveAllComments()
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim sql As String = "UPDATE UserComments SET Status=" + DirectCast(UserComment.Status.ucsAccepted, Integer) + " WHERE AboutUID=@AboutUID" + Environment.NewLine + " AND Status=" + DirectCast(UserComment.Status.ucsNewAccepted, Integer)

				Dim cmd As New SqlCommand(sql)
				cmd.Connection = conn

				cmd.Parameters.Add("@AboutUID", Me.id)

				cmd.ExecuteNonQuery()
			Finally
				conn.Close()
			End Try
		End Sub



		Public Sub ChangeNewStatus(ByVal userID As Integer)
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim sql As String = ""
				'sql = "UPDATE UserComments SET Status=" + (int)UserComment.Status.ucsAccepted + " WHERE AboutUID=@AboutUID" + Environment.NewLine;
				If Me.ApproveComments Then
					sql = "UPDATE UserComments SET Status=" + DirectCast(UserComment.Status.ucsNewAccepted, Integer) + " WHERE AboutUID=@AboutUID" + Environment.NewLine + " AND Status=" + DirectCast(UserComment.Status.ucsNew, Integer)
				Else
					sql = "UPDATE UserComments SET Status=" + DirectCast(UserComment.Status.ucsNew, Integer) + " WHERE AboutUID=@AboutUID" + Environment.NewLine + " AND Status=" + DirectCast(UserComment.Status.ucsNewAccepted, Integer)
				End If

				Dim cmd As New SqlCommand(sql)
				cmd.Connection = conn

				cmd.Parameters.Add("@AboutUID", userID)

				cmd.ExecuteNonQuery()
			Finally
				conn.Close()
			End Try
		End Sub

		Protected Sub ApproveAllPictureComments()
			For Each pic As UserPicture In GetPictures()
				For Each upc As PictureComment In pic.NewComments
					pic.ApproveComment(upc.ID, True)
				Next
			Next
		End Sub

		Protected Sub ApproveAllBlogComments(ByVal userID As Integer)
			For Each blog As Blog In Messages.GetUserBlogs(userID)
				For Each blogComment As Blog In Messages.GetNotApprovedBlogEntries(blog.ID)
					blogComment.Approve()
					blogComment.Save()
				Next
			Next
		End Sub

		Public ReadOnly Property NewComments() As ArrayList
			Get
				Return GetNewComments()
			End Get
		End Property

		Public ReadOnly Property NewNotAcceptedComments() As ArrayList
			Get
				Return GetNewNotAcceptedComments()
			End Get
		End Property

		Public ReadOnly Property Comments() As ArrayList
			Get
				Return GetApprovedComments()
			End Get
		End Property


		'
		' Private and protected methods
		'

		Protected Function GetNewComments() As ArrayList
			Dim cl As New ArrayList()

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As SqlCommand = Nothing
				If Me.ApproveComments Then
					cmd = New SqlCommand("SELECT * FROM UserComments WHERE AboutUID=@AboutUID AND Status=" + DirectCast(UserComment.Status.ucsNewAccepted, Integer) + " ORDER BY DATE DESC")
				Else
					cmd = New SqlCommand("SELECT * FROM UserComments WHERE AboutUID=@AboutUID AND Status=" + DirectCast(UserComment.Status.ucsNew, Integer) + " ORDER BY DATE DESC")
				End If

				cmd.Connection = conn
				cmd.Parameters.Add("@AboutUID", id)

				Dim dr As SqlDataReader = cmd.ExecuteReader()
				While dr.Read()
					cl.Add(New UserComment(dr))
				End While
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return cl
		End Function

		Protected Function GetNewNotAcceptedComments() As ArrayList
			Dim cl As New ArrayList()

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As SqlCommand = Nothing
				cmd = New SqlCommand("SELECT * FROM UserComments WHERE AboutUID=@AboutUID AND Status=" + DirectCast(UserComment.Status.ucsNew, Integer) + " ORDER BY DATE DESC")

				cmd.Connection = conn
				cmd.Parameters.Add("@AboutUID", id)

				Dim dr As SqlDataReader = cmd.ExecuteReader()
				While dr.Read()
					cl.Add(New UserComment(dr))
				End While
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return cl
		End Function

		Protected Function GetApprovedComments() As ArrayList
			Dim cl As New ArrayList()

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As SqlCommand = Nothing
				If Me.ApproveComments Then
					cmd = New SqlCommand("SELECT * FROM UserComments WHERE AboutUID=@AboutUID AND ( Status=" + DirectCast(UserComment.Status.ucsNewAccepted, Integer) + " OR Status=" + DirectCast(UserComment.Status.ucsAccepted, Integer) + " ) ORDER BY DATE DESC")
				Else
					cmd = New SqlCommand("SELECT * FROM UserComments WHERE AboutUID=@AboutUID AND Status=" + DirectCast(UserComment.Status.ucsAccepted, Integer) + " ORDER BY DATE DESC")
				End If
				cmd.Connection = conn
				cmd.Parameters.Add("@AboutUID", id)

				Dim dr As SqlDataReader = cmd.ExecuteReader()
				While dr.Read()
					cl.Add(New UserComment(dr))
				End While
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return cl
		End Function

		Protected Sub Init(ByVal userEmail As String, ByVal userPass As String, ByVal refererID As Integer)
			id = -1
			name = ""
			lastName = ""
			email = userEmail
			nickName = ""
			passHash = Users.ComputeUserHash(userEmail, userPass)
			gender = -1
			birthDay = DateTime.MinValue
			genderPreference = -1
			matesSR = False
			matesPen = False
			matesFriends = False
			matesDating = False
			matesAP = False
			matesJHO = False
			Me.refererID = refererID
			showOnline = True
			interests = ""
			coutryID = -1
			city = ""
			zip = ""
			placeOfBirth = ""
			maritalStatus = 0
			occupation = ""
			templateID = -1
			bgImageURL = ""
			wavURL = ""
			defaultPictureID = -1
			aboutMe = ""
			lookingFor = ""
			affiliations = ""
			companies = ""
			schools = ""
			songURL1 = ""
			songURLName1 = ""
			songURL2 = ""
			songURLName2 = ""
			songURL3 = ""
			songURLName3 = ""
			imageURL = ""
			imageURLName = ""
			music = ""
			books = ""
			tv = ""
			movies = ""
			registrationDate = DateTime.Now
			editDate = DateTime.Now
			loginDate = DateTime.MinValue
			enableEmailNotify = True
			enableGroupEmailNotify = True
			enableNewsletter = True
			status = Users.STATUS_UNCONFIRMED
			timesViewed = -1
			approveComments = True
			approveBlogComments = True
			approveFriends = True

			forumPassHash = FormsAuthentication.HashPasswordForStoringInConfigFile(userPass, "md5")
			chatPass = userPass
		End Sub

		Protected Sub LoadFromReader(ByVal dr As SqlDataReader)
			id = dr.GetInt32(dr.GetOrdinal("ID"))

			name = DBManager.GetNZString(dr, "Name")

			lastName = DBManager.GetNZString(dr, "LastName")

			email = dr.GetString(dr.GetOrdinal("Email"))

			nickName = dr.GetString(dr.GetOrdinal("Nickname"))

			passHash = dr.GetString(dr.GetOrdinal("Password"))

			gender = dr.GetInt32(dr.GetOrdinal("Gender"))

			birthDay = DBManager.GetNZDateTime(dr, "Date_of_birth")

			genderPreference = dr.GetInt32(dr.GetOrdinal("GenderPreference"))

			matesSR = DBManager.GetNZBool(dr, "Mates_SR")

			matesPen = DBManager.GetNZBool(dr, "Mates_Pen")

			matesFriends = DBManager.GetNZBool(dr, "Mates_Friends")

			matesDating = DBManager.GetNZBool(dr, "Mates_Dating")

			matesAP = DBManager.GetNZBool(dr, "Mates_AP")

			matesJHO = DBManager.GetNZBool(dr, "Mates_JHO")

			refererID = DBManager.GetNZInt32(dr, "Referrer")

			showOnline = (DBManager.GetNZInt32(dr, "ShowOnline") = 1)

			interests = DBManager.GetNZString(dr, "Interests")

			coutryID = DBManager.GetNZInt32(dr, "CountryID")

			city = DBManager.GetNZString(dr, "City")

			zip = DBManager.GetNZString(dr, "ZipCode")

			placeOfBirth = DBManager.GetNZString(dr, "Place_of_birth")

			maritalStatus = dr.GetInt32(dr.GetOrdinal("MeritalStatus"))

			occupation = DBManager.GetNZString(dr, "Occupation")

			templateID = DBManager.GetNZInt32(dr, "TemplateID")

			bgImageURL = DBManager.GetNZString(dr, "BGImageURL")

			wavURL = DBManager.GetNZString(dr, "WAVURL")

			defaultPictureID = DBManager.GetNZInt32(dr, "DefaultPictureID")

			aboutMe = DBManager.GetNZString(dr, "AboutMe")

			lookingFor = DBManager.GetNZString(dr, "LookingFor")

			affiliations = DBManager.GetNZString(dr, "Affiliations")

			companies = DBManager.GetNZString(dr, "Companies")

			schools = DBManager.GetNZString(dr, "Schools")

			songURL1 = DBManager.GetNZString(dr, "SongURL1")

			songURLName1 = DBManager.GetNZString(dr, "SongURLName1")

			songURL2 = DBManager.GetNZString(dr, "SongURL2")

			songURLName2 = DBManager.GetNZString(dr, "SongURLName2")

			songURL3 = DBManager.GetNZString(dr, "SongURL3")

			songURLName3 = DBManager.GetNZString(dr, "SongURLName3")

			imageURL = DBManager.GetNZString(dr, "ImageURL")

			imageURLName = DBManager.GetNZString(dr, "ImageURLName")

			music = DBManager.GetNZString(dr, "Music")

			books = DBManager.GetNZString(dr, "Books")

			tv = DBManager.GetNZString(dr, "TV")

			movies = DBManager.GetNZString(dr, "Movies")

			registrationDate = dr.GetDateTime(dr.GetOrdinal("Date"))

			editDate = dr.GetDateTime(dr.GetOrdinal("LastEditedDate"))

			loginDate = DBManager.GetNZDateTime(dr, "LastLoginDate")

			enableEmailNotify = dr.GetBoolean(dr.GetOrdinal("Notify"))

			enableNewsletter = dr.GetBoolean(dr.GetOrdinal("Newsletter"))

			status = dr.GetInt32(dr.GetOrdinal("Status"))

			timesViewed = dr.GetInt32(dr.GetOrdinal("TimesViewed"))

			approveComments = dr.GetBoolean(dr.GetOrdinal("ApproveComments"))

			enableGroupEmailNotify = dr.GetBoolean(dr.GetOrdinal("GroupNotify"))

			approveBlogComments = dr.GetBoolean(dr.GetOrdinal("ApproveBlogComments"))

			approveFriends = dr.GetBoolean(dr.GetOrdinal("ApproveFriends"))
		End Sub

		Protected Sub DoDelete()
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				' Delete all groups, where the user is a moderator
				For Each grp As Group In Groups.MyModeratedGroups(ID)
					grp.DoDelete()
				Next

				' Delete the user
				Dim cmd As New SqlCommand(GetDeleteSQL())
				cmd.Connection = conn

				cmd.Parameters.Add("@ID", id)

				Dim rows As Integer = cmd.ExecuteNonQuery()
				Debug.Assert(rows = 1)

				' Mark the user object as non-existing (new), keeping the old password
				Dim oldPassHash As String = passHash
				Init(email, passHash, refererID)
				passHash = oldPassHash
			Finally
				conn.Close()
			End Try
		End Sub

		Protected Sub DoInsert()
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()
			Dim tran As SqlTransaction = conn.BeginTransaction()

			Try
				' Insert the user
				Dim cmd As New SqlCommand(GetInsertSQL())
				cmd.Connection = conn
				cmd.Transaction = tran

				PopulateCommand(cmd)

				Dim rows As Integer = cmd.ExecuteNonQuery()
				Debug.Assert(rows = 1)

				' Reload the user
				DoRefresh(tran)

				tran.Commit()
			Catch e As Exception
				tran.Rollback()
				Throw e
			Finally
				conn.Close()
			End Try
		End Sub

		Protected Sub DoUpdate()
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand(GetUpdateSQL())
				cmd.Connection = conn

				PopulateCommand(cmd)

				cmd.Parameters.Add("@ID", id)

				Dim rows As Integer = cmd.ExecuteNonQuery()
				Debug.Assert(rows = 1)

				ChangeNewStatus(id)
				' This is called no matter of approval, the 2 different cases are inserted in the function logic
				If approveComments Then
					ApproveAllPictureComments()
				End If

				If approveBlogComments Then
					ApproveAllBlogComments(id)
				End If
			Finally
				conn.Close()
			End Try
		End Sub

		Protected Sub DoRefresh()
			DoRefresh(Nothing)
		End Sub

		Protected Sub DoRefresh(ByVal sqlTrans As SqlTransaction)
			Dim conn As SqlConnection = Nothing
			Dim ownConnection As Boolean = False

			If sqlTrans = Nothing Then
				conn = DBManager.GetUnmanagedConnection()
				ownConnection = True
			Else
				conn = sqlTrans.Connection
			End If

			Try
				Dim cmd As New SqlCommand("SELECT * FROM Users WHERE Email=@Email")
				cmd.Connection = conn
				If Not ownConnection Then
					cmd.Transaction = sqlTrans
				End If

				cmd.Parameters.Add("@Email", email)

				Dim dr As SqlDataReader = cmd.ExecuteReader()

				Dim found As Boolean = dr.Read()
				Debug.Assert(found)
				LoadFromReader(dr)

				dr.Close()
			Finally
				If ownConnection Then
					conn.Close()
				End If
			End Try
		End Sub

		Private Shared Function GetDeleteSQL() As String
			Dim sql As String = "DELETE FROM Users" + Environment.NewLine
			sql += "WHERE" + Environment.NewLine
			sql += "" & Chr(9) & "ID=@ID" + Environment.NewLine
			Return sql
		End Function

		Private Shared Function GetInsertSQL() As String
			Dim sql As String = "INSERT INTO Users" + Environment.NewLine
			sql += "( Name, LastName, Email, Nickname, Password, Gender, Date_of_birth, GenderPreference, " + "Mates_SR, Mates_Pen, Mates_Friends, Mates_Dating, Mates_AP, Mates_JHO, " + "Referrer, ShowOnline, Interests, CountryID, City, ZipCode, Place_of_birth, MeritalStatus, Occupation, " + "TemplateID, BGImageURL, WAVURL, DefaultPictureID, AboutMe, LookingFor, " + "Affiliations, Companies, Schools, " + "SongURL1, SongURLName1, SongURL2, SongURLName2, SongURL3, SongURLName3, ImageURL, ImageURLName, " + "Music, Books, TV, Movies, Newsletter, LastEditedDate, Notify, Status )" + Environment.NewLine
			sql += "VALUES" + Environment.NewLine
			sql += "( @Name, @LastName, @Email, @Nickname, @Password, @Gender, @Date_of_birth, @GenderPreference, " + "@Mates_SR, @Mates_Pen, @Mates_Friends, @Mates_Dating, @Mates_AP, @Mates_JHO, " + "@Referrer, @ShowOnline, @Interests, @CountryID, @City, @ZipCode, @Place_of_birth, @MeritalStatus, @Occupation, " + "@TemplateID, @BGImageURL, @WAVURL, @DefaultPictureID, @AboutMe, @LookingFor, " + "@Affiliations, @Companies, @Schools, " + "@SongURL1, @SongURLName1, @SongURL2, @SongURLName2, @SongURL3, @SongURLName3, @ImageURL, @ImageURLName, " + "@Music, @Books, @TV, @Movies, @Newsletter, @LastEditedDate, @Notify, @Status )" + Environment.NewLine
			Return sql
		End Function

		Private Shared Function GetUpdateSQL() As String
			Dim sql As String = "UPDATE Users SET" + Environment.NewLine
			sql += "" & Chr(9) & "Name=@Name," + Environment.NewLine
			sql += "" & Chr(9) & "LastName=@LastName," + Environment.NewLine
			sql += "" & Chr(9) & "Email=@Email," + Environment.NewLine
			sql += "" & Chr(9) & "Nickname=@Nickname," + Environment.NewLine
			sql += "" & Chr(9) & "Password=@Password," + Environment.NewLine
			sql += "" & Chr(9) & "Gender=@Gender," + Environment.NewLine
			sql += "" & Chr(9) & "Date_of_birth=@Date_of_birth," + Environment.NewLine
			sql += "" & Chr(9) & "GenderPreference=@GenderPreference," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_SR=@Mates_SR," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_Pen=@Mates_Pen," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_Friends=@Mates_Friends," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_Dating=@Mates_Dating," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_AP=@Mates_AP," + Environment.NewLine
			sql += "" & Chr(9) & "Mates_JHO=@Mates_JHO," + Environment.NewLine
			sql += "" & Chr(9) & "Referrer=@Referrer," + Environment.NewLine
			sql += "" & Chr(9) & "ShowOnline=@ShowOnline," + Environment.NewLine
			sql += "" & Chr(9) & "Interests=@Interests," + Environment.NewLine
			sql += "" & Chr(9) & "CountryID=@CountryID," + Environment.NewLine
			sql += "" & Chr(9) & "City=@City," + Environment.NewLine
			sql += "" & Chr(9) & "ZipCode=@ZipCode," + Environment.NewLine
			sql += "" & Chr(9) & "Place_of_birth=@Place_of_birth," + Environment.NewLine
			sql += "" & Chr(9) & "MeritalStatus=@MeritalStatus," + Environment.NewLine
			sql += "" & Chr(9) & "Occupation=@Occupation," + Environment.NewLine
			sql += "" & Chr(9) & "TemplateID=@TemplateID," + Environment.NewLine
			sql += "" & Chr(9) & "BGImageURL=@BGImageURL," + Environment.NewLine
			sql += "" & Chr(9) & "WAVURL=@WAVURL," + Environment.NewLine
			sql += "" & Chr(9) & "DefaultPictureID=@DefaultPictureID," + Environment.NewLine
			sql += "" & Chr(9) & "AboutMe=@AboutMe," + Environment.NewLine
			sql += "" & Chr(9) & "LookingFor=@LookingFor," + Environment.NewLine
			sql += "" & Chr(9) & "Affiliations=@Affiliations," + Environment.NewLine
			sql += "" & Chr(9) & "Companies=@Companies," + Environment.NewLine
			sql += "" & Chr(9) & "Schools=@Schools," + Environment.NewLine
			sql += "" & Chr(9) & "SongURL1=@SongURL1," + Environment.NewLine
			sql += "" & Chr(9) & "SongURLName1=@SongURLName1," + Environment.NewLine
			sql += "" & Chr(9) & "SongURL2=@SongURL2," + Environment.NewLine
			sql += "" & Chr(9) & "SongURLName2=@SongURLName2," + Environment.NewLine
			sql += "" & Chr(9) & "SongURL3=@SongURL3," + Environment.NewLine
			sql += "" & Chr(9) & "SongURLName3=@SongURLName3," + Environment.NewLine
			sql += "" & Chr(9) & "ImageURL=@ImageURL," + Environment.NewLine
			sql += "" & Chr(9) & "ImageURLName=@ImageURLName," + Environment.NewLine
			sql += "" & Chr(9) & "Music=@Music," + Environment.NewLine
			sql += "" & Chr(9) & "Books=@Books," + Environment.NewLine
			sql += "" & Chr(9) & "TV=@TV," + Environment.NewLine
			sql += "" & Chr(9) & "Movies=@Movies," + Environment.NewLine
			sql += "" & Chr(9) & "Newsletter=@Newsletter," + Environment.NewLine
			sql += "" & Chr(9) & "LastEditedDate=@LastEditedDate," + Environment.NewLine
			sql += "" & Chr(9) & "Notify=@Notify," + Environment.NewLine
			sql += "" & Chr(9) & "Status=@Status," + Environment.NewLine
			sql += "" & Chr(9) & "TimesViewed=@TimesViewed," + Environment.NewLine
			sql += "" & Chr(9) & "ApproveComments=@ApproveComments," + Environment.NewLine
			sql += "" & Chr(9) & "GroupNotify=@GroupNotify," + Environment.NewLine
			sql += "" & Chr(9) & "ApproveBlogComments=@ApproveBlogComments," + Environment.NewLine
			sql += "" & Chr(9) & "ApproveFriends=@ApproveFriends" + Environment.NewLine
			sql += "WHERE" + Environment.NewLine
			sql += "" & Chr(9) & "ID=@ID" + Environment.NewLine
			Return sql
		End Function

		Private Shared Function GetPicturesSQL() As String
			Dim sql As String = "SELECT pics.*," + Environment.NewLine
			sql += "" & Chr(9) & "CASE" + Environment.NewLine
			sql += "" & Chr(9) & "" & Chr(9) & "WHEN (pics.ID = usrs.DefaultPictureID) THEN 1" + Environment.NewLine
			sql += "" & Chr(9) & "" & Chr(9) & "ELSE 0" + Environment.NewLine
			sql += "" & Chr(9) & "END AS IS_DEFAULT" + Environment.NewLine
			sql += "FROM" + Environment.NewLine
			sql += "" & Chr(9) & "Pictures pics," + Environment.NewLine
			sql += "" & Chr(9) & "Users usrs" + Environment.NewLine
			sql += "WHERE" + Environment.NewLine
			sql += "" & Chr(9) & "pics.UID = usrs.ID" + Environment.NewLine
			sql += "AND" & Chr(9) & "UID=@UID" + Environment.NewLine
			Return sql
		End Function

		Private Shared Function GetPicturesTotalLengthSQL() As String
			Dim sql As String = "SELECT SUM(DATALENGTH(Picture)) as TotalLength" + Environment.NewLine
			sql += "FROM" + Environment.NewLine
			sql += "" & Chr(9) & "Pictures pics," + Environment.NewLine
			sql += "" & Chr(9) & "Users usrs" + Environment.NewLine
			sql += "WHERE" + Environment.NewLine
			sql += "" & Chr(9) & "pics.UID = usrs.ID" + Environment.NewLine
			sql += "AND" & Chr(9) & "UID=@UID" + Environment.NewLine
			Return sql
		End Function

		Private Shared Function GetDeletePictureSQL() As String
			Dim sql As String = "DELETE FROM Pictures" + Environment.NewLine
			sql += "WHERE" + Environment.NewLine
			sql += "" & Chr(9) & "ID=@ID" + Environment.NewLine
			Return sql
		End Function

		' Populates the command with the user's properties
		' NOTE: skips the ID property, since it's need only on insert
		Private Sub PopulateCommand(ByVal cmd As SqlCommand)
			DBManager.SetNZValue(cmd, "@Name", name)
			DBManager.SetNZValue(cmd, "@LastName", lastName)
			cmd.Parameters.Add("@Email", email)
			cmd.Parameters.Add("@Nickname", nickName)
			cmd.Parameters.Add("@Password", passHash)
			cmd.Parameters.Add("@Gender", gender)
			Console.Write("birthDay = " + birthDay)
			DBManager.SetNZValue(cmd, "@Date_of_birth", birthDay)
			cmd.Parameters.Add("@GenderPreference", genderPreference)
			cmd.Parameters.Add("@Mates_SR", matesSR)
			cmd.Parameters.Add("@Mates_Pen", matesPen)
			cmd.Parameters.Add("@Mates_Friends", matesFriends)
			cmd.Parameters.Add("@Mates_Dating", matesDating)
			cmd.Parameters.Add("@Mates_AP", matesAP)
			cmd.Parameters.Add("@Mates_JHO", matesJHO)
			DBManager.SetNZValue(cmd, "@Referrer", refererID)
			cmd.Parameters.Add("@ShowOnline", showOnline)
			DBManager.SetNZValue(cmd, "@Interests", interests)
			DBManager.SetNZValue(cmd, "@CountryID", coutryID)
			DBManager.SetNZValue(cmd, "@City", city)
			DBManager.SetNZValue(cmd, "@ZipCode", zip)
			DBManager.SetNZValue(cmd, "@Place_of_birth", placeOfBirth)
			cmd.Parameters.Add("@MeritalStatus", maritalStatus)
			DBManager.SetNZValue(cmd, "@Occupation", occupation)
			DBManager.SetNZValue(cmd, "@TemplateID", templateID)
			DBManager.SetNZValue(cmd, "@BGImageURL", bgImageURL)
			DBManager.SetNZValue(cmd, "@WAVURL", wavURL)
			DBManager.SetNZValue(cmd, "@DefaultPictureID", defaultPictureID)
			cmd.Parameters.Add("@Status", status)

			DBManager.SetNZValue(cmd, "@AboutMe", aboutMe)
			DBManager.SetNZValue(cmd, "@LookingFor", lookingFor)
			DBManager.SetNZValue(cmd, "@Affiliations", affiliations)
			DBManager.SetNZValue(cmd, "@Companies", companies)
			DBManager.SetNZValue(cmd, "@Schools", schools)
			DBManager.SetNZValue(cmd, "@SongURL1", songURL1)
			DBManager.SetNZValue(cmd, "@SongURLName1", songURLName1)
			DBManager.SetNZValue(cmd, "@SongURL2", songURL2)
			DBManager.SetNZValue(cmd, "@SongURLName2", songURLName2)
			DBManager.SetNZValue(cmd, "@SongURL3", songURL3)
			DBManager.SetNZValue(cmd, "@SongURLName3", songURLName3)
			DBManager.SetNZValue(cmd, "@ImageURL", imageURL)
			DBManager.SetNZValue(cmd, "@ImageURLName", imageURLName)
			DBManager.SetNZValue(cmd, "@Music", music)
			DBManager.SetNZValue(cmd, "@Books", books)
			DBManager.SetNZValue(cmd, "@TV", tv)
			DBManager.SetNZValue(cmd, "@Movies", movies)

			cmd.Parameters.Add("@LastEditedDate", editDate)
			cmd.Parameters.Add("@Notify", enableEmailNotify)
			cmd.Parameters.Add("@Newsletter", enableNewsletter)
			cmd.Parameters.Add("@TimesViewed", timesViewed)
			cmd.Parameters.Add("@ApproveComments", approveComments)
			cmd.Parameters.Add("@GroupNotify", enableGroupEmailNotify)
			cmd.Parameters.Add("@ApproveBlogComments", approveBlogComments)
			cmd.Parameters.Add("@ApproveFriends", approveFriends)
		End Sub

		Private Sub SaveUserToChatDB()
		'String username, String password, String location, String occupation, String interests, Boolean gender, int age

			Dim conn As New SqlConnection(Constants.CHAT_DB_CONN_STRING)
			Dim cmd As New SqlCommand("insert into Users (Username, Password, DisplayName, Location, Occupation, Interests, Age, Gender,LastLoginTime,DateCreated) values (@Username, @Password, @DisplayName, @Location, @Occupation, @Interests, @Age, @Gender,GETDATE(),GETDATE())", conn)
			'SqlCommand cmd = new SqlCommand("insert into Users (Username, Password, Location, Occupation, Interests, Age, Gender,LastLoginTime,DateCreated) values (@Username, @Password, @Location, @Occupation, @Interests, @Age, @Gender,GETDATE(),GETDATE())", conn);

			Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar)
			paraUsername.Value = email

			Dim paraPassword As SqlParameter = cmd.Parameters.Add("@Password", SqlDbType.NVarChar)
			paraPassword.Value = chatPass

			Dim paraDisplayName As SqlParameter = cmd.Parameters.Add("@DisplayName", SqlDbType.NVarChar)
			paraDisplayName.Value = name
			' + " " + lastName;
			Dim paraLocation As SqlParameter = cmd.Parameters.Add("@Location", SqlDbType.NVarChar)
			paraLocation.Value = city + (IIf(city <> String.Empty,", ","")) + Constants.COUNTRIES.GetCountryByID(CountryID).Name

			Dim paraOccupation As SqlParameter = cmd.Parameters.Add("@Occupation", SqlDbType.NVarChar)
			paraOccupation.Value = occupation

			Dim paraInterests As SqlParameter = cmd.Parameters.Add("@Interests", SqlDbType.NVarChar)
			paraInterests.Value = interests

			Dim paraAge As SqlParameter = cmd.Parameters.Add("@Age", SqlDbType.Int, 4)
			paraAge.Value = 0
			'age				
			Dim paraGender As SqlParameter = cmd.Parameters.Add("@Gender", SqlDbType.Bit)
			paraGender.Value = (IIf(gender <> 1,0,1))

			Try
				conn.Open()
				cmd.ExecuteNonQuery()
			Catch e As Exception
					'new Exception("Cannot add user to Chat DB");
				Throw e
			Finally

				conn.Close()
			End Try

			' Add new user to "Members" role
			AddUserToChatRole("Members", email)

		End Sub

		Private Sub AddUserToChatRole(ByVal roleName As String, ByVal username As String)
			Dim conn As New SqlConnection(Constants.CHAT_DB_CONN_STRING)
			Dim cmd As New SqlCommand("Insert into UserRole (Username, RoleName) values (@Username, @RoleName)", conn)

			Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar)
			paraUsername.Value = username

			Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar)
			paraRoleName.Value = roleName

			Try
				conn.Open()
				cmd.ExecuteNonQuery()
			Catch
				Throw New Exception("Cannot add user to Chat Role")
			Finally
				conn.Close()
			End Try
		End Sub

		Private Function CreatePassword(ByVal length As Integer) As String
			Dim valid As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
			Dim res As String = ""
			Dim rnd As New Random()
			While 0 < System.Math.Max(System.Threading.Interlocked.Decrement(length),length + 1)
				res += valid(rnd.[Next](valid.Length))
			End While
			Return res
		End Function

		Private Sub SaveUserToForumDB()
		'object UserID,object boardID,object UserName,object Password,object Email,object Hash,
'			object Location,object HomePage,object TimeZone,object Avatar,
'			object languageFile,object themeFile,object Approved,
'			object msn,object yim,object aim,object icq,
'			object realName,object occupation,object interests,object gender,object weblog
			Const  GMT As Integer = 0
			Dim hashinput As String = DateTime.Now.ToString() + email + CreatePassword(20)
			Dim hash As String = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5")

			Using cmd As New SqlCommand("yaf_user_save")
				cmd.CommandType = CommandType.StoredProcedure
				cmd.Parameters.Add("@UserID", id)
				cmd.Parameters.Add("@BoardID", Convert.ToInt32(Constants.FORUM_BOARD_ID))
				cmd.Parameters.Add("@UserName", email)
				cmd.Parameters.Add("@Password", passHash)
				cmd.Parameters.Add("@Email", email)
				cmd.Parameters.Add("@Hash", hash)
				cmd.Parameters.Add("@Location", city + (IIf(city <> String.Empty,", ","")) + Constants.COUNTRIES.GetCountryByID(CountryID).Name)
				cmd.Parameters.Add("@HomePage", Nothing)
				cmd.Parameters.Add("@TimeZone", GMT)
				cmd.Parameters.Add("@Avatar", Nothing)
				cmd.Parameters.Add("@LanguageFile", Nothing)
				cmd.Parameters.Add("@ThemeFile", Nothing)
				'				cmd.Parameters.Add("@Location",Location);
				'				cmd.Parameters.Add("@HomePage",HomePage);
				'				cmd.Parameters.Add("@TimeZone",TimeZone);
				'				cmd.Parameters.Add("@Avatar",Avatar);
				'				cmd.Parameters.Add("@LanguageFile",languageFile);
				'				cmd.Parameters.Add("@ThemeFile",themeFile);
				cmd.Parameters.Add("@Approved", Users.FORUM_APPROVED)
				cmd.Parameters.Add("@MSN", Nothing)
				cmd.Parameters.Add("@YIM", Nothing)
				cmd.Parameters.Add("@AIM", Nothing)
				cmd.Parameters.Add("@ICQ", Nothing)
				'				cmd.Parameters.Add("@MSN",msn);
				'				cmd.Parameters.Add("@YIM",yim);
				'				cmd.Parameters.Add("@AIM",aim);
				'				cmd.Parameters.Add("@ICQ",icq);
				cmd.Parameters.Add("@RealName", name)
				'+ " " + lastName);
				cmd.Parameters.Add("@Occupation", occupation)
				cmd.Parameters.Add("@Interests", interests)
				cmd.Parameters.Add("@Gender", gender)
				cmd.Parameters.Add("@Weblog", Nothing)
				'				cmd.Parameters.Add("@Weblog",weblog);

				'QueryCounter qc = new QueryCounter(cmd.CommandText);
				Dim conn As SqlConnection = DBManager.GetUnmanagedForumDBConnection()
				Try
					Using conn
						Using trans As SqlTransaction = conn.BeginTransaction()
							cmd.Connection = conn
							cmd.Transaction = trans
							cmd.ExecuteNonQuery()
							trans.Commit()
						End Using
					End Using
				Catch generatedExceptionName As Exception
					Throw New Exception("Cannot add user to Forum DB")
					

				Finally
					'qc.Dispose();
					conn.Close()
				End Try
			End Using
		End Sub
	End Class
End Namespace






